#include "syncdialog.h"

SyncDialog::SyncDialog(QWidget *parent, Qt::WFlags f) : QWidget(parent, f) {
	setupUi(this);
	status = SyncManager::DISCONNECT;
	console->setAutoFillBackground(true);
}

SyncDialog::~SyncDialog() {
}

void SyncDialog::on_syncButton_clicked() {
	QString ipStr;
	QString portStr;
	QString result = "";
	switch (status) {	
	case SyncManager::DISCONNECT:
		//===== disconnect -> connecting
		ipStr = ipLineEdit->text();
		portStr = portLineEdit->text();		
		if (!SyncManager::validateIp(ipStr)) {
			result += "Invalid Ip address\n";
		}
		if (!SyncManager::validatePort(portStr)) {
			result += "Invalid port number\n";
		}
		if (result.length() != 0) {
			QMessageBox::warning(this, "Warning.",
			result, QMessageBox::Ok);
		} else {
			emit connectSignal(ipStr, portStr);
			updateStatus(SyncManager::CONNECTING);
		}
		break;
	case SyncManager::CONNECTING:
		//===== connecting -> disconnect
		emit disconnectSignal();
		updateStatus(SyncManager::DISCONNECT);
		break;
	case SyncManager::CONNECT:
		//===== connect -> disconnect
		emit disconnectSignal();
		updateStatus(SyncManager::DISCONNECT);
		break;	
	}
}

void SyncDialog::updateStatus(int status) {
	qDebug() << "SyncDialog::updateStatus |";
	switch (status) {
	case SyncManager::CONNECT:
		qDebug() << "CONNECT";
		this->status = SyncManager::CONNECT;
		updateView("Connection established.\n Synchronising...");
		break;
	case SyncManager::CONNECTING:
		qDebug() << "CONNECTING";
		this->status = SyncManager::CONNECTING;
		updateView("Establishing Connection...");
		break;
	case SyncManager::SYNCED:
		qDebug() << "SYNCED";
		this->status = SyncManager::CONNECT;
		updateView("Connection established.\n Synchronised.");
		hide();
		emit statusSignal(SyncManager::SYNCED);
		break;
	case SyncManager::DISCONNECT:
		qDebug() << "DISCONNECT";
		this->status = SyncManager::DISCONNECT;
		updateView("Connection abort.");
		emit statusSignal(SyncManager::DISCONNECT);
		break;
	case SyncManager::ERROR_ADDRESS:		
		this->status = SyncManager::DISCONNECT;
		updateView("Invalid address.");
		break;
	case SyncManager::ERROR_NETWORK:
		qDebug() << "ERROR_NETWORK";
		this->status = SyncManager::DISCONNECT;
		updateView("Unable to connect to the host.");
		emit statusSignal(SyncManager::ERROR_NETWORK);
		break;
	default:
		updateView("Unsupport status happened.");
	}
}

void SyncDialog::updateView(QString message) {
	switch (status) {
	case SyncManager::DISCONNECT:
		ipLineEdit->setEnabled(true);
		portLineEdit->setEnabled(true);
		syncButton->setText("Connect");
		statusLabel->setText("Disconnect");
		break;
	case SyncManager::CONNECT:
		ipLineEdit->setEnabled(false);
		portLineEdit->setEnabled(false);
		syncButton->setText("Disconnect");
		statusLabel->setText("Connect");
		break;
	case SyncManager::CONNECTING:
		ipLineEdit->setEnabled(false);
		portLineEdit->setEnabled(false);
		syncButton->setText("Disconnect");
		statusLabel->setText("Disconnect");
		break;
	}	
	console->setText(message);
}

